#!/bin/bash

# ========================================
# DevToolsNav Nginx 配置部署脚本
# ========================================

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}DevToolsNav Nginx 配置部署${NC}"
echo -e "${GREEN}========================================${NC}\n"

# 检查是否在正确的目录
if [ ! -f "devtoolsnav-host.conf" ]; then
    echo -e "${RED}❌ 错误：请在 deploy/nginx 目录下运行此脚本${NC}"
    exit 1
fi

echo -e "${YELLOW}步骤1: 停止Nginx${NC}"
sudo systemctl stop nginx

echo -e "\n${YELLOW}步骤2: 清理旧的devtoolsnav配置${NC}"
sudo rm -f /etc/nginx/sites-enabled/devtoolsnav*
sudo rm -f /etc/nginx/sites-available/devtoolsnav*

echo -e "\n${YELLOW}步骤3: 复制新配置到Nginx${NC}"
sudo cp devtoolsnav-host.conf /etc/nginx/sites-available/devtoolsnav.com
echo -e "${GREEN}✅ 配置文件已复制${NC}"

echo -e "\n${YELLOW}步骤4: 启用站点${NC}"
sudo ln -sf /etc/nginx/sites-available/devtoolsnav.com /etc/nginx/sites-enabled/
echo -e "${GREEN}✅ 站点已启用${NC}"

echo -e "\n${YELLOW}步骤5: 测试Nginx配置${NC}"
if sudo nginx -t; then
    echo -e "${GREEN}✅ Nginx配置测试通过${NC}"
else
    echo -e "${RED}❌ Nginx配置测试失败${NC}"
    exit 1
fi

echo -e "\n${YELLOW}步骤6: 启动Nginx${NC}"
sudo systemctl start nginx

echo -e "\n${YELLOW}步骤7: 检查Nginx状态${NC}"
sudo systemctl status nginx --no-pager | head -10

echo -e "\n${YELLOW}步骤8: 等待3秒后测试${NC}"
sleep 3

echo -e "\n${YELLOW}步骤9: 测试API访问${NC}"
echo "测试后端直接访问:"
curl http://localhost:4002/api/categories 2>/dev/null | head -c 100 && echo ""

echo -e "\n测试通过域名访问:"
curl https://devtoolsnav.com/api/categories 2>/dev/null | head -c 100 && echo ""

echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}✅ Nginx配置部署完成！${NC}"
echo -e "${GREEN}========================================${NC}\n"

echo -e "🌐 现在可以访问："
echo -e "  - https://devtoolsnav.com"
echo -e "\n📝 查看日志："
echo -e "  - sudo tail -f /var/log/nginx/devtoolsnav-access.log"
echo -e "  - sudo tail -f /var/log/nginx/devtoolsnav-error.log"

